package com.lhkj.ct.base.mybatis.extension.service;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lhkj.ct.base.utils.Asserts;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.Objects;

/**
 * @Description: 基础接口
 */
public interface IService<T> {

    default int insert(T entity) { return this.getBaseMapper().insert(entity); }

    default int updateById(T entity) { return this.getBaseMapper().updateById(entity); }

    default T getById(Serializable id) {
        return this.getBaseMapper().selectById(id);
    }

    default int removeById(Serializable id) { return this.getBaseMapper().deleteById(id); }

//    default int removeByIds(Serializable... ids) { return this.getBaseMapper().deleteBatchIds(Arrays.asList(ids)); }

    default int removeByIds(Collection<? extends Serializable> idList) { return this.getBaseMapper().deleteBatchIds(idList); }

    BaseMapper<T> getBaseMapper();

    Class<T> getEntityClass();

    @Transactional(rollbackFor = {Exception.class})
    default int saveOrUpdate(T entity) {
        if (null == entity) {
            return 0;
        } else {
            TableInfo tableInfo = TableInfoHelper.getTableInfo(this.getEntityClass());
            Asserts.assertNotNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");
            String keyProperty = tableInfo.getKeyProperty();
            Asserts.assertNotEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!");
            Object idVal = tableInfo.getPropertyValue(entity, tableInfo.getKeyProperty());
            return !StringUtils.checkValNull(idVal) && !Objects.isNull(this.getById((Serializable) idVal)) ? this.updateById(entity) : this.insert(entity);
        }
    }
}
